package com.fy.springmvc2.utils;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;

import java.io.IOException;
import java.lang.reflect.Type;

/** 自定义序列化 */
public class MySerializer implements ObjectSerializer {
    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {

       /** 将某个字段的值 四舍五入  在实体类加注解@JsonSerialize(using = MySerializer.class)*/
//        Double value =(Double) object;
//        String number = BigDecimal.valueOf(value).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
//        // 输出 四舍五入后的值
//        serializer.write(number);
//

        /**实现某个字段属性值的拼接返回到前端  在实体类加注解@JsonSerialize(using = MySerializer.class)*/
        Double value =(Double) object;//salary属性值
        String text = value + "元";//在salary后拼接 “元”
        //{"birthday":"2022-05-05 09:51:32","id":1,"marryDay":"2022-05-05 09:51:32","salary":"900.546元","username":""}
        serializer.write(text);// 输出拼接后的内容

    }
}
